"""
测试CNN模型的精确度
"""
import glob
import config
import numpy as np
import tensorflow as tf
from skimage import io, transform


MODEL_WIDTH = config.MODEL_WIDTH
MODEL_HEIGHT = config.MODEL_HEIGHT
MODEL_CHANNEL = config.MODEL_CHANNEL
BATCH_SIZE = config.CNN_BATCH_SIZE
IMAGES_DIR = glob.glob('./Testsets/Images/' + '*.bmp')
LABELS_DIR = './Testsets/labels.txt'
MODEL_DIR = './Model/model.meta'


# 读取图片
def read_images(path_list):
    img_list = []
    for path in path_list:
        img = io.imread(path)
        img = transform.resize(img, (MODEL_WIDTH, MODEL_HEIGHT))
        img = np.asarray(img)
        img_list.append(img)
    return img_list


# 读取label值
def read_labels(path_list):
    file_label = open(path_list, 'r')
    label_list = []
    for line in file_label:
        line = line.strip('\n')
        label_list.append(line)
    return label_list


if __name__ == '__main__':
    index_list = read_labels(LABELS_DIR)    # 读取标签
    # 测试
    with tf.Session() as sess:
        # 导入模型
        saver = tf.train.import_meta_graph(MODEL_DIR)
        saver.restore(sess, tf.train.latest_checkpoint('Model/'))
        # 导入计算图
        graph = tf.get_default_graph()
        x = graph.get_tensor_by_name("input/x:0")
        # 导入测试数据集
        corrected = 0
        output = []
        batch_num = int(len(IMAGES_DIR) / BATCH_SIZE)
        for i in range(batch_num):
            feed_dict = {x: read_images(IMAGES_DIR[BATCH_SIZE * i: BATCH_SIZE * (i + 1)])}
            logits = graph.get_tensor_by_name("logits_eval:0")
            classification_result = sess.run(logits, feed_dict)
            # 输出预测矩阵每一行最大值的索引
            output.extend(tf.argmax(classification_result, 1).eval())
        for i in range(len(index_list)):
            print(index_list[i], output[i])
            if int(index_list[i]) == int(output[i]):
                corrected += 1
        print('ACC: %.4f' % (corrected / len(index_list)))
